import axios from  "@ohos/axios"
import hilog from '@ohos.hilog';

import { RequestOptions, BaseResultBean } from '../bean'

const BASE_URL = "http://changjia2020.fm924.com"

/**
 * 发送请求
 */
async function sendRequest<T>(
    url: string,
    method: string,
    data?: object,
):Promise<T> {
  axios.defaults.headers.common = {
    'User-Type': 'app',
    'envParam': '{"appVersion":"6.0.12","deviceCode":60012,"deviceManufacturer":"Xiaomi","deviceModel":"23013RK75C","deviceVersion":"14","isDeviceRooted":false,"isEmulator":false}',
    'Host': 'changjia2020.fm924.com',
    Authorization: 'Basic Y2hhbmdqaWFfdG1pc19hcHA6Y2hhbmdqaWFfdG1pc19zZWNyZXRfYXBw',
    clientType: 10,
  }
  axios.defaults.baseURL = BASE_URL;
  try {
    const obj = {
      url,
      method,
    }
    if (method === 'get') {
      Object.assign(obj, { params: data })
    } else {
      Object.assign(obj, { data })
    }
    const res = await axios<BaseResultBean<T>>(obj)
    if (res.data.success){
      hilog.info(0xFF00, "axios:info", "%{public}s:%{public}s:SUCCESS", method.toUpperCase(), url);
    } else {
      hilog.error(0xFF00, "axios:info", "%{public}s:%{public}s:ERROR, ERROR_MSG:%{public}s", method.toUpperCase(), url, res.data.msg);
    }
    return res.data.data
  } catch (e) {
    hilog.error(0xFF00, "axios:info", "%{public}s:%{public}s:ERROR, ERROR_INFO:%{public}s", method.toUpperCase(), url, JSON.stringify(e));
    return null;
  }
}

export class ApiRequest {
  static async get<T>(
    options: RequestOptions
  ): Promise<T> {
    return sendRequest<T>(options.url,
      'get',
      options.data)
  }

  static async post<T>(
    options: RequestOptions
  ): Promise<T> {
    return sendRequest(options.url,
      'post',
      options.data,
     )
  }
}